package com.lkd.handler;

import com.github.wxpay.plus.WxPayParam;
import com.github.wxpay.plus.WxPayTemplate;
import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.OrderCheck;
import com.lkd.emq.Topic;
import com.lkd.entity.OrderEntity;
import com.lkd.exception.LogicException;
import com.lkd.service.OrderService;
import com.lkd.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Objects;

/**
 * @author brianxia
 * @version 1.0
 * @date 2022-12-21 10:51
 */
@Component
@Topic(TopicConfig.ORDER_CHECK_TOPIC)
@Slf4j
public class OrderCheckHandler implements MsgHandler {

    @Autowired
    private OrderService orderService;
    @Autowired
    private WxPayTemplate wxPayTemplate;

    @Override
    public void process(String jsonMsg) throws IOException {

        //1.接收消息，判断消息参数
        OrderCheck orderCheck = JsonUtil.getByJson(jsonMsg, OrderCheck.class);
        if(orderCheck == null || StringUtils.isEmpty(orderCheck.getOrderNo())){
            return;
        }

        //2.查询订单
        OrderEntity orderEntity = orderService.getByOrderNo(orderCheck.getOrderNo());
        if(orderEntity == null){
            log.error("订单编号不存在!" + jsonMsg);
            return;
        }

        //3.如果订单未支付，取消订单
        if(Objects.equals(orderEntity.getPayStatus(),VMSystem.PAY_STATUS_NOPAY)){
            orderEntity.setStatus(VMSystem.ORDER_STATUS_INVALID);
            orderService.updateById(orderEntity);

            //4.调用微信支付系统接口，取消二维码
            WxPayParam wxPayParam = new WxPayParam();
            wxPayParam.setOutTradeNo(orderEntity.getOrderNo());
            try {
                wxPayTemplate.closeOrder(wxPayParam);
            } catch (Exception e) {
               log.error("调用微信关单接口失败" + jsonMsg,e);
            }
        }


    }
}
